#pragma once
#include <iostream>
#include <string>
#include <fstream>
#include<unordered_map>
#include"log.hpp"
const std::string default_dictname = "dict.txt";
const std::string default_dictpath = "/home/dyx/gitee/linux/UDP_dict_server/";
const std::string default_gap = ":";
bool Split(const std::string &line, std::string *key, std::string *value, const std::string &gap = default_gap)
{   //china: 中国
    auto pos = line.find(gap);
    if(pos == std::string::npos)
        return false;
    *key = line.substr(0, pos);//左闭右开
    *value = line.substr(pos + gap.size());
    if(key->empty() || value->empty())return false;
    return true;
}

class Dict{
    private:
        bool LoadDict()
        {
            std::string file = _dict_path + _dict_name;
            std::ifstream in(file.c_str());
            if(!in.is_open()){
                LOG(log_level::ERROR)<<"Failed to open file: "<<file;
                return false;
            }
            std::string line;
            while(std::getline(in,line)){
                std::string key, value;
                if(Split(line, &key, &value, default_gap)){
                    _dict.insert(std::make_pair(key, value));
                }
            }
            in.close();
            return true;    
        }

    public:
        Dict(const std::string &dict_path = default_dictpath, const std::string &dict_name = default_dictname)
            : _dict_path(dict_path), _dict_name(dict_name)
        {
            if(LoadDict())
                LOG(log_level::INFO)<<"Dict loaded successfully.";
            else
                LOG(log_level::INFO)<<"Failed to load dict.";
        }
        
        std::string Translate(const std::string &word)
        {
            auto it = _dict.find(word);
            if(it != _dict.end()){
                return it->second;
            }
            return "None";
        }

        
        ~Dict()
        {

        }
    private:
        std::unordered_map<std::string, std::string> _dict;
        std::string _dict_path;
        std::string _dict_name;
};

